package com.css.fxfzypg.modules.model.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.BeanUtil;
import com.css.fxfzypg.modules.model.entity.Material;
import com.css.fxfzypg.modules.model.repository.MaterialRepository;
import com.css.fxfzypg.modules.model.service.MaterialService;
import com.css.fxfzypg.modules.model.vo.MaterialVO;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Dbj
 * @date 2022年10月05日  17:36
 */
@Service
public class MaterialServiceImpl implements MaterialService {

    @Resource
    private MaterialRepository materialRepository;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    SUserService sUserService;

    @Resource
    private SysRoleService roleService;

    @Resource
    private SysAreaService areaService;

    @Override
    public Map<String, Object> getPage(MaterialVO vo, int curPage, int pageSize) {
        Map<String,String> areaMap =(Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaMap"));
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        String userId = PlatformSessionContext.getUserID();
        vo.setUserId(userId);
        //根据用户id查询角色信息 用于数据的查询范围
        String roleByUserId = roleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(roleByUserId, Map.class);
        for(Map roleMap:roleMaps){
            String roleCode =  (String)roleMap.get("roleCode");
            if(roleCode.equals(FxfzConstants.YPG_COUN_YW_ROLE) || roleCode.equals(FxfzConstants.YPG_COUN_GL_ROLE)){
                vo.setNation(true);
            }
        }
        if(vo.getNation()==null){
            vo.setNation(false);
        }
        Map<String, Object> page = materialRepository.findPage(vo, curPage, pageSize);
        List<Material> list = (List<Material>) page.get("rows");
        for(Material material:list){
            material.setProvince(areaMap.get(material.getProvince()));
            if(!"全部".equals(material.getCity())){
                StringBuffer buffer = new StringBuffer();
                List<String> cityList = Arrays.asList(material.getCity().split(","));
                for (String s : cityList) {
                    buffer.append(areaMap.get(s)).append(",");
                }
                String cityName = buffer.toString();
                material.setCity(cityName.substring(0,cityName.length()-1));
            }
        }
        page.put("rows",list);
        return page;
    }

    @Override
    public Material getModelById(String id) {
        Map<String,String> areaMap =(Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaMap"));
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        Material material = materialRepository.getModelById(id);
        material.setProvince(areaMap.get(material.getProvince()));
        if(!"全部".equals(material.getCity())){
            StringBuffer buffer = new StringBuffer();
            List<String> cityList = Arrays.asList(material.getCity().split(","));
            for (String s : cityList) {
                buffer.append(areaMap.get(s)).append(",");
            }
            String cityName = buffer.toString();
            material.setCity(cityName.substring(0,cityName.length()-1));
        }
//        CasualtyVO vo = new CasualtyVO();
//        BeanUtil.copy(casualty,vo);
        return material;
    }

    @Override
    public Material getDefaultModel() {
        return materialRepository.getDefaultModel();
    }

    @Override
    public List<Material> getByDivision(String province, String city, int isNa) {
        return materialRepository.getByDivision(province,city,isNa);
    }

    @Override
    public Material getModelByIdForCopy(String id) {
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        Material material = materialRepository.getModelById(id);
        material.setModelName("");
        material.setIsDefault("0");
        material.setCity("");
        material.setProvince("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        material.setCreateUserId(userId);
        material.setCreateUserName(sUser.getUserName());
        material.setOrgId(sUser.getOrgId());
        material.setOrgName(orgMap.get(sUser.getOrgId()));
        material.setIsValid(YNEnum.Y.toString());
        return material;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Material material) {
        Map<String,String> orgMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"orgMap"));
        String userId = PlatformSessionContext.getUserID();
        material.setId(UUIDGenerator.getUUID());
        material.setCreateUserId(userId);
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        material.setCreateUserName(sUser.getUserName());
        material.setCreateTime(new Date());
        material.setOrgId(sUser.getOrgId());
        String orgName = orgMap.get(sUser.getOrgId());
        material.setOrgName(orgName);
        material.setIsValid(YNEnum.Y.toString());
        String areaCode = areaService.getDivisionCodeById(material.getProvince());
        areaCode =(String) JSONObject.parse(areaCode);
        material.setProvinceCode(areaCode);
        materialRepository.save(material);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Material material) {
        Material ma = materialRepository.getModelById(material.getId());
        String userId = PlatformSessionContext.getUserID();
        if(!userId.equals(ma.getCreateUserId())){
            throw new RuntimeException("修改失败，只能修改自己创建的模型");
        }
        BeanUtil.copy(material,ma);
        material.setUpdateUserId(userId);
        material.setUpdateTime(new Date());
        materialRepository.update(material);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        Material material = materialRepository.getModelById(id);
        String userId = PlatformSessionContext.getUserID();
        if(!userId.equals(material.getCreateUserId())){
            throw new RuntimeException("删除失败，只能删除自己创建的模型");
        }
        materialRepository.delete(userId,new Date(),id);
    }

    //ss
    @Override
    public Material getModel1ById(String id) {
        Material material = materialRepository.getModelById(id);
        return material;
    }
}
